<template>
  <div class="progressive-image-container" ref="imageContainer">
    <div class="loading-skeleton" :class="{ hidden: isOriginalLoaded }">
      <a-spin v-if="!isOriginalLoaded" />
    </div>
    <img
      :src="thumbnailSrc"
      :alt="alt"
      class="thumbnail"
      :class="{ loaded: isOriginalLoaded }"
      loading="lazy"
    />
    <img
      :src="getResponsiveImageUrl(originalSrc)"
      :srcset="generateSrcSet(originalSrc)"
      :sizes="sizes"
      :alt="alt"
      class="original"
      :class="{ loaded: isOriginalLoaded }"
      loading="lazy"
      @load="onOriginalLoad"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { Spin } from 'ant-design-vue';

interface Props {
  originalSrc: string;
  thumbnailSrc?: string;
  alt?: string;
  sizes?: string;
}

const props = withDefaults(defineProps<Props>(), {
  thumbnailSrc: '',
  alt: '',
  sizes: '(max-width: 768px) 100vw, 50vw'
});

const isOriginalLoaded = ref(false);
const imageContainer = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;

// 生成响应式图片URL
const getResponsiveImageUrl = (url: string) => {
  // 移除现有的尺寸参数（如果有）
  const baseUrl = url.split('?')[0];
  // 根据设备DPR添加适当的尺寸
  const dpr = window.devicePixelRatio || 1;
  const defaultWidth = 800;
  return `${baseUrl}?w=${defaultWidth * dpr}`;
};

// 生成srcset属性
const generateSrcSet = (url: string) => {
  const baseUrl = url.split('?')[0];
  const widths = [400, 800, 1200, 1600];
  return widths
    .map(width => `${baseUrl}?w=${width} ${width}w`)
    .join(', ');
};

// 图片加载完成处理
const onOriginalLoad = () => {
  isOriginalLoaded.value = true;
};

// 设置Intersection Observer
const setupIntersectionObserver = () => {
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 当图片进入视口时，开始加载原图
          const originalImg = entry.target.querySelector('.original') as HTMLImageElement;
          if (originalImg) {
            originalImg.src = getResponsiveImageUrl(props.originalSrc);
          }
          // 停止观察
          observer?.unobserve(entry.target);
        }
      });
    },
    {
      rootMargin: '50px 0px',
      threshold: 0.1
    }
  );

  if (imageContainer.value) {
    observer.observe(imageContainer.value);
  }
};

onMounted(() => {
  if ('IntersectionObserver' in window) {
    setupIntersectionObserver();
  }
});

onUnmounted(() => {
  if (observer) {
    observer.disconnect();
  }
});
</script>

<style scoped>
.progressive-image-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #f5f5f5;
}

.loading-skeleton {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease-in-out;
}

.loading-skeleton.hidden {
  opacity: 0;
  pointer-events: none;
}

.loading-animation {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #6893AC;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.thumbnail,
.original {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail {
  filter: blur(10px);
  transform: scale(1.1);
  transition: opacity 0.3s ease-in-out;
}

.original {
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.thumbnail.loaded {
  opacity: 0;
}

.original.loaded {
  opacity: 1;
}
</style>